﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using Kotonoha.Server.Objects.Model;

namespace Kotonoha.Server.Model {
    public class CSVReader : IEnumerable<Word> {
        private readonly StreamReader reader;

        public CSVReader(Stream stream, Encoding enc) {
            reader = new StreamReader(stream, enc);
        }


        public IEnumerator<Word> GetEnumerator() {
            return new CVSParser(reader);
        }

        private class CVSParser : IEnumerator<Word> {
            private readonly StreamReader reader;
            private Word currentWord;

            public CVSParser(StreamReader reader) {
                this.reader = reader;
            }

            public void Dispose() {
                reader.Close();
            }

            public bool MoveNext() {
                string line;

                while (!canRead(line = reader.ReadLine())) {
                    if (reader.EndOfStream) {
                        return false;
                    }
                }

                currentWord = new Word();

                string[] tokens = line.Trim().Split('\t');

                switch(tokens.Length) {
                    default:
                        currentWord.Translations = new[] {kill(tokens[2])};
                        goto case 2;
                    case 2:
                        currentWord.Reading = tokens[1];
                        goto case 1;
                    case 1:
                        currentWord.Writing = tokens[0];
                        break;
                    case 0:
                        //lol wtf;
                        return false;
                }

                WordFiller.fillCommonInWord(currentWord);

                return true;
            }

            Regex regex = new Regex(@"<.+?>");
            private string kill(string s) {
                return regex.Replace(s, "").Trim();
            }

            private static bool canRead(string s) {
                return !string.IsNullOrEmpty(s) && s[0] != '\t';
            }

            public void Reset() {
                throw new NotImplementedException();
            }

            public Word Current {
                get { return currentWord; }
            }

            object IEnumerator.Current {
                get { return Current; }
            }
        }

        IEnumerator IEnumerable.GetEnumerator() {
            return GetEnumerator();
        }
    }
}